<template>
    <div class="createPost-container">
        <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

            <sticky :z-index="10" class-name="sub-navbar">
                <el-tooltip class="item" effect="dark" content="选择文章状态" placement="left">
                    <el-select v-model="postForm.newsStatus" placeholder="请选择大类状态" style="width: 120px;">
                        <el-option label="显示" :value="1" />
                        <el-option label="隐藏" :value="0" />
                    </el-select>
                </el-tooltip>
                <SourceUrlDropdown v-model="postForm.source_uri" style="margin-left: 10px;" />
                <el-button v-loading="loading" style="margin-left: 10px;" :type="isEdit? 'primary' : 'success'" @click="submitForm">
                    {{ isEdit? '保存文章' : '发布文章' }}
                </el-button>
            </sticky>

            <div class="createPost-main-container">
                <el-row>
                    <el-col :span="24">
                        <el-form-item style="margin-bottom: 40px;" prop="title">
                            <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                                文章标题
                            </MDinput>
                        </el-form-item>

                        <div class="postInfo-container">
                            <el-row>
                                <el-col :span="8">
                                    <el-form-item prop="authorName" label-width="60px" label="作者:" class="postInfo-container-item">
                                        <el-input v-model="postForm.authorName" placeholder="请输入作者/来源" />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item prop="catId" label-width="120px" label="所属大类:" class="postInfo-container-item">
                                        <el-cascader
                                            v-model="postForm.catId"
                                            placeholder="大类名称"
                                            :options="options"
                                            :props="props"
                                            collapse-tags
                                            clearable
                                        />
                                    </el-form-item>
                                </el-col>

                                <!--                                <el-col :span="6">-->
                                <!--                                    <el-form-item label-width="90px" label="状态:" class="postInfo-container-item">-->
                                <!--                                        <el-select v-model="postForm.status" placeholder="请选择大类状态">-->
                                <!--                                            <el-option label="显示" :value="1" />-->
                                <!--                                            <el-option label="隐藏" :value="0" />-->
                                <!--                                        </el-select>-->
                                <!--                                    </el-form-item>-->
                                <!--                                </el-col>-->
                            </el-row>
                        </div>
                    </el-col>
                </el-row>

                <el-form-item prop="description" style="margin-bottom: 40px;" label-width="60px" label="描述:">
                    <el-input
                        v-model="postForm.description"
                        :rows="1"
                        type="textarea"
                        class="article-textarea"
                        autosize
                        placeholder="请输入文章描述.."
                        @input="handleDescription"
                    />
                    <span v-show="contentShortLength" class="word-counter" :style="{color: contentShortLength>=100? 'red': ''}">{{ contentShortLength }}words</span>
                </el-form-item>

                <el-form-item prop="content" style="margin-bottom: 30px;">
                    <Tinymce ref="editor" v-model="content" :height="400" />
                </el-form-item>

                <p class="title">文章封面图片</p>
                <el-form-item style="margin-bottom: 30px;">
                    <Upload v-model="postForm.img" />
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import Upload from '@/components/Upload/SingleImage3'
import { validURL } from '@/utils/validate'
import { SourceUrlDropdown } from './Dropdown'
import { getCategoryTree } from '@/api/category'
import { createPost, getPostDetail, updatePost } from '@/api/post'

const defaultForm = {
    catId: [], // 所属大类id
    newsStatus: 0, // 文章状态 隐藏/显示
    authorName: '', // 来源
    title: '', // 文章题目
    description: '', // 文章摘要
    source_uri: '', // 文章外链
    img: '', // 文章简介图片
    id: undefined
}

export default {
    name: 'ArticleDetail',
    components: { Tinymce, MDinput, Upload, Sticky, SourceUrlDropdown },
    props: {
        isEdit: {
            type: Boolean,
            default: false
        }
    },
    data() {
        const validateRequire = (rule, value, callback) => {
            if (value === '') {
                callback(new Error(rule.field + '为必传项'))
            } else if (value && value.length === 0) {
                setTimeout(() => {
                    this.$message({
                        message: '必须选择文章所属大类',
                        type: 'error'
                    })
                }, 0)
                callback(new Error('必须选择文章所属大类'))
            } else {
                callback()
            }
        }
        const validateSourceUri = (rule, value, callback) => {
            if (value) {
                if (validURL(value)) {
                    callback()
                } else {
                    this.$message({
                        message: '外链url填写不正确',
                        type: 'error'
                    })
                    callback(new Error('外链url填写不正确'))
                }
            } else {
                callback()
            }
        }
        return {
            postForm: Object.assign({}, defaultForm), // 文章信息
            content: '', // 文章内容
            loading: false,
            rules: {
                title: [{ validator: validateRequire }],
                authorName: [{ validator: validateRequire }],
                catId: [{ validator: validateRequire }],
                description: [{ validator: validateRequire }],
                source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
            },
            affiliates: [], // 当前所属级联大类
            props: { // 级联选择框规则
                value: 'id',
                label: 'name'
            },
            options: []
        }
    },
    computed: {
        contentShortLength() {
            return this.postForm.description.length
        }
    },
    created() {
        const _id = this.$route.params && this.$route.params.id
        // 获取级联选择器大类树
        getCategoryTree({ include: 'home' }).then(data => {
            this.options = data
        })
        // 获取文章数据
        if (this.isEdit) {
            this.fetchData(_id)
        }
    },
    methods: {
        fetchData(id) {
            getPostDetail(id).then(data => {
                this.postForm = data.news
                this.content = data.newsContent.content
                this.setPageTitle()
            }).catch(err => {
                console.log(err)
            })
        },
        setPageTitle() {
            const title = '编辑文章'
            document.title = `${title} - ${this.postForm.id}`
        },
        submitForm() {
            this.$refs.postForm.validate(valid => {
                if (valid) {
                    // 判断content是否为空
                    if (this.content === '') {
                        this.$message.error('文章内容不能为空!')
                        return
                    }
                    // 开始加载
                    this.loading = true
                    const _postForm = Object.assign({}, this.postForm)
                    // 设置所属大类
                    _postForm.catId = this.postForm.catId[this.postForm.catId.length - 1]
                    // 返回对象
                    const _data = {
                        news: _postForm,
                        newsContent: {
                            content: this.content
                        }
                    }
                    if (this.isEdit) {
                        updatePost(this.postForm.id, _data).then(() => {
                            this.loading = false
                            this.$notify({
                                keywords: '成功',
                                message: '文章保存成功',
                                type: 'success',
                                duration: 2000
                            })
                        })
                    } else {
                        createPost(_data).then(() => {
                            this.loading = false
                            this.$notify({
                                keywords: '成功',
                                message: '发布文章成功',
                                type: 'success',
                                duration: 2000
                            })
                            setTimeout(() => {
                                this.backToList()
                                this.postForm = Object.assign({}, defaultForm)
                            }, 1000)
                        }).catch(err => {
                            this.loading = false
                            console.log(err)
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 限制描述字数
        handleDescription(val) {
            if (val && val.length > 100) {
                this.postForm.description = val.slice(0, 100)
            }
        },
        // 返回列表
        backToList() {
            this.$router.push('/post/list')
        }
    }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.title{
    margin-top: 45px;
}
</style>
